package com.test07.image;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.imageio.IIOImage;
import javax.imageio.ImageIO;
import javax.imageio.ImageTypeSpecifier;
import javax.imageio.ImageWriter;
import javax.imageio.metadata.IIOMetadata;
import javax.imageio.plugins.jpeg.JPEGImageWriteParam;
import javax.imageio.stream.ImageOutputStream;

/**
 * @author zhouqz
 */
public class ImgCompressUtil {
	/**
	 * 图片压缩测试
	 * 
	 * @throws Exception
	 */
	@SuppressWarnings("resource")
	public static void main(String args[]) throws Exception {
		// 源文件
		FileInputStream fileInputStream = new FileInputStream("D:\\upload\\5.png");
		// 目的文件
		FileOutputStream fileOutputStream = new FileOutputStream("D:\\upload\\6.png");

//		compressImageByDefault(fileInputStream, fileOutputStream);
		compressImageByCompression(fileInputStream, fileOutputStream, 0.5f);

		fileInputStream.close();
		fileOutputStream.close();
	}

	/**
	 * 使用默认的方式进行压缩
	 */
	private static void compressImageByDefault(InputStream inputStream, OutputStream outputStream) throws Exception {
		// 得到图片的抽象对象
		BufferedImage bufferedImage = ImageIO.read(inputStream);
		// 得到处理后图片对象
		Image image = bufferedImage.getScaledInstance(bufferedImage.getWidth(), bufferedImage.getHeight(),
				Image.SCALE_SMOOTH);
		// 开始执行转换操作
		bufferedImage.getGraphics().drawImage(image, 0, 0, null);
		// 写到输出流
		ImageIO.write(bufferedImage, "jpg", outputStream);
	}

	/**
	 * 可以设置压缩率的压缩方式
	 */
	private static void compressImageByCompression(InputStream inputStream, OutputStream outputStream,
			float JPEGcompression) throws Exception {
		// 得到图片的抽象对象
		BufferedImage bufferedImage = ImageIO.read(inputStream);
		// 根据jpg创建一个imageWriter
		ImageWriter imageWriter = ImageIO.getImageWritersBySuffix("jpg").next();
		// 根据输出流，创建图片输出流
		ImageOutputStream ios = ImageIO.createImageOutputStream(outputStream);
		imageWriter.setOutput(ios);
		// 创建导出设置
		JPEGImageWriteParam jpegParams = null;
		if (JPEGcompression >= 0 && JPEGcompression <= 1f) {
			jpegParams = (JPEGImageWriteParam) imageWriter.getDefaultWriteParam();
			jpegParams.setCompressionMode(JPEGImageWriteParam.MODE_EXPLICIT);
			jpegParams.setCompressionQuality(JPEGcompression);
		}
		// 根据设置写入到输出流中
		IIOMetadata imageMetaData = imageWriter.getDefaultImageMetadata(new ImageTypeSpecifier(bufferedImage), null);
		imageWriter.write(imageMetaData, new IIOImage(bufferedImage, null, null), jpegParams);
		// 关闭
		ios.close();
		imageWriter.dispose();
	}
}